package cn.xuqiudong.demo.mvc.redis.subscribe;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalTime;

/**
 * 说明: redis  订阅发布配置
 *
 * @author Vic.xu
 * @since 2023/4/28/0028 16:49
 */
@Configuration
@EnableScheduling
public class RedisSubscribeConfig {

    public static final String TEST_CHANNEL = "channel:test:one";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 配置redis 订阅监听相关
     * @param redisConnectionFactory redis factory
     * @param testRedisMessageListener redis message listener
     * @return RedisMessageListenerContainer
     */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory,
                                                                       TestRedisMessageListener testRedisMessageListener){
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        //订阅频道，可以订阅多个
        redisMessageListenerContainer.addMessageListener(testRedisMessageListener, new ChannelTopic(TEST_CHANNEL)) ;


        /*
         *  RedisMessageListenerContainer 一可以加上消息监听器适配器，绑定消息处理器，利用反射技术调用消息处理器的业务方法
         *  定消息处理器的被反射的防范参数为消息内容
         *  MessageListenerAdapter  adapter = new MessageListenerAdapter(spring bean, method name)
         *   redisMessageListenerContainer.addMessageListener(adapter, new PatternTopic(TEST_CHANNEL)) ;
         */

        return  redisMessageListenerContainer;

    }


    @Scheduled(initialDelay = 1000, fixedRate = 60000 )
    public void send(){
        redisTemplate.convertAndSend(TEST_CHANNEL, LocalTime.now() + " 测试订阅发布");
    }

}
